package com.ErpCoreWeb.View;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ErpCoreModel.Base.CUser;
import com.ErpCoreModel.Framework.CBaseObject;
import com.ErpCoreModel.Framework.CColumn;
import com.ErpCoreModel.Framework.CTable;
import com.ErpCoreModel.Framework.Util;
import com.ErpCoreModel.UI.CView;
import com.ErpCoreModel.UI.CViewCatalog;
import com.ErpCoreModel.UI.CViewDetail;
import com.ErpCoreModel.UI.enumViewType;
import com.ErpCoreWeb.Common.Global;

/**
 * Servlet implementation class MasterDetailViewInfo1
 */
@WebServlet("/MasterDetailViewInfo1")
public class MasterDetailViewInfo1 extends HttpServlet {
	private static final long serialVersionUID = 1L;

	HttpServletRequest request;
	HttpServletResponse response;

    public CView m_View = null;
    public UUID m_Catalog_id = Util.GetEmptyUUID();
    boolean m_bIsNew = false;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MasterDetailViewInfo1() {
        super();
        // TODO Auto-generated constructor stub
    }

    //初始化变量
    void initData()
    {
        if (request.getSession().getAttribute("User") == null)
        {
            try {
            	response.getWriter().print("请重新登录！");
            	response.getWriter().close();
            	//response.getWriter().print("{success:false,err:'',url:'../Login.jsp'}");
				//response.sendRedirect("../Login.jsp");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            
            return ;
        }
		
		String id = request.getParameter("id");
        if (!Global.IsNullParameter(id))
        {
            m_View = (CView)Global.GetCtx(this.getServletContext()).getViewMgr().Find(Util.GetUUID(id));
        }
        else
        {
            m_bIsNew = true;
            if (request.getSession().getAttribute("NewMasterDetailView") == null)
            {
                m_View = new CView();
                m_View.Ctx = Global.GetCtx(this.getServletContext());
                m_View.setVType (enumViewType.MasterDetail);
                CViewDetail ViewDetail = new CViewDetail();
                ViewDetail.Ctx = m_View.Ctx;
                ViewDetail.setUI_View_id ( m_View.getId());
                m_View.getViewDetailMgr().AddNew(ViewDetail);

                Map<UUID, CView> sortObj = new HashMap<UUID, CView>();
                sortObj.put(m_View.getId(), m_View);
                request.getSession().setAttribute("NewMasterDetailView", sortObj);
            }
            else
            {
            	Map<UUID, CView> sortObj = (Map<UUID, CView>)request.getSession().getAttribute("NewMasterDetailView");
                m_View =(CView) sortObj.values().toArray()[0];
            }
        }
        String catalog_id = request.getParameter("catalog_id");
        if (!Global.IsNullParameter(catalog_id))
        {
            m_Catalog_id = Util.GetUUID(catalog_id);
        }
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}
	void doProc(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{

		this.request=request;
		this.response=response;

		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");

		//初始化变量
	    initData();
	    //
        String Action = request.getParameter("Action");
        if (Action == null) Action = "";

        if (Action.equalsIgnoreCase("LoadColumn"))
        {
        	LoadColumn();
            return ;
        }
        else if (Action.equalsIgnoreCase("Next"))
        {
        	Next();
            return ;
        }
        else if (Action.equalsIgnoreCase("Cancel"))
        {
        	request.getSession().setAttribute("NewMasterDetailView", null);
            return ;
        }
	}

	void Next()
	{
		if (!ValidatePage1())
            return;
        if (!SavePage1())
            return;
        
	}

    boolean ValidatePage1()
    {
		try {
			String txtName = request.getParameter("txtName");
			if (Global.IsNullParameter(txtName)) {
				response.getWriter().print("名称不能空！");
				return false;
			}
			String sTbId = request.getParameter("cbMasterTable");
			if (Global.IsNullParameter(sTbId)) {
				response.getWriter().print("请选择主表！");
				return false;
			}
			CTable tbM = (CTable) Global.GetCtx(this.getServletContext())
					.getTableMgr().Find(Util.GetUUID(sTbId));
			sTbId = request.getParameter("cbDetailTable");
			if (Global.IsNullParameter(sTbId)) {
				response.getWriter().print("请选择从表！");
				return false;
			}
			CTable tbD = (CTable) Global.GetCtx(this.getServletContext())
					.getTableMgr().Find(Util.GetUUID(sTbId));
			if (tbM.getId().equals(tbD.getId())) {
				response.getWriter().print("主表不能与从表相同！");
				return false;
			}
			String cbPrimaryKey = request.getParameter("cbPrimaryKey");
			if (Global.IsNullParameter(cbPrimaryKey)) {
				response.getWriter().print("请设置外键关联！");
				return false;
			}
			String cbForeignKey = request.getParameter("cbForeignKey");
			if (Global.IsNullParameter(cbForeignKey)) {
				response.getWriter().print("请设置外键关联！");
				return false;
			}

			return true;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
    }

    boolean SavePage1()
    {
		String sName = request.getParameter("txtName");
        if (!sName.equalsIgnoreCase(m_View.getName()))
        {
            CView view2 = Global.GetCtx(this.getServletContext()).getViewMgr().FindByName(sName);
            if (view2 != null)
            {
            	try {
					response.getWriter().print("名称重复！");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
                return false;
            }
        }
        m_View.setName ( sName);
		m_View.setUI_ViewCatalog_id (m_Catalog_id);
        //如果是修改，并修改了主表，则清空旧字段
		String cbMasterTable = request.getParameter("cbMasterTable");
        UUID guidMT = Util.GetUUID(cbMasterTable);
        if (!m_bIsNew && !guidMT.equals(m_View.getFW_Table_id()))
        {
            m_View.getColumnInViewMgr().RemoveAll();
        }
        m_View.setFW_Table_id ( guidMT);
        CViewDetail ViewDetail = (CViewDetail)m_View.getViewDetailMgr().GetFirstObj();
        //如果是修改，并修改了从表，则清空旧字段
		String cbDetailTable = request.getParameter("cbDetailTable");
        UUID guidDT = Util.GetUUID(cbDetailTable);
        if (!m_bIsNew && !guidDT.equals(ViewDetail.getFW_Table_id()))
        {
            ViewDetail.getColumnInViewDetailMgr().RemoveAll();
        }
        ViewDetail.setFW_Table_id ( guidDT);
		String cbPrimaryKey = request.getParameter("cbPrimaryKey");
        ViewDetail.setPrimaryKey (Util.GetUUID(cbPrimaryKey));
		String cbForeignKey = request.getParameter("cbForeignKey");
        ViewDetail.setForeignKey (Util.GetUUID(cbForeignKey));

        m_View.getViewDetailMgr().Update(ViewDetail);



        return true;
    }
    
    void LoadColumn()
    {
        String sJson="";
		String sTbId = request.getParameter("table_id");
        CTable table = (CTable)Global.GetCtx(this.getServletContext()).getTableMgr().Find(Util.GetUUID(sTbId));
        List<CBaseObject> lstObj = table.getColumnMgr().GetList();
        for (CBaseObject obj : lstObj)
        {
            CColumn column = (CColumn)obj;
            sJson += String.format("{ text: '%s', id: '%s' },",column.getName(), column.getId().toString());
        }
    	if (sJson.endsWith(","))
    		sJson = sJson.substring(0, sJson.length() - 1);
    	sJson = "[" + sJson + "]";
    	
    	try {
			response.getWriter().print( sJson);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
}
